<template v-if="bye">
  <div class="box">
    <baseContent ref="baseContentRef">
    <template #header>
      <div class="smart-clip-header">
        <div class="smart-clip-header-title_top">矩阵管理</div>
        <div class="smart-clip-header-desc">
          <!-- <div></div> -->
          <div>
            授权注意事项：<br />授权后尽量保证授权账号保持正常在线状态，无异常操作（否则授权会有概率失效）。
          </div>
          <div>
            授权账号与{{
              appName
            }}客户端登录电脑，应争取在同一地区IP，否则可能出现二次验证或授权失效等问题。
          </div>
        </div>
      </div>
    </template>

    <template #sticky>
      <a-space class="mt-20">
      <!-- :disabled="addTotal <= 0" -->
      <a-button
        :disabled="addTotal <= 0"
        type="primary"
        @click="addAuthorization"
      >
        添加账号
      </a-button>
      <!-- <a-button
        type="primary"
        @click="SynchronousAccount"
        :loading="syncLoading"
        v-if="org_count > 0"
        >同步子账号</a-button
      > -->
      <a-button type="default" @click="showSettingGroup" class="btn-primary"
        >设置分组</a-button
      >
      <a-button
        type="default"
        :loading="alldel_loading"
        @click="goToGroup"
        class="btn-primary"
      >
        <!-- @click="addGroup" -->
        分组管理
      </a-button>

      <a-button type="default" @click="debouncedall_del" class="btn-primary">
        批量删除
      </a-button>

      <a-button type="default" @click="debouncedall_index" class="btn-primary">
        批量设置员工运营
      </a-button>
    </a-space>
    <div class="flex justify-between align-center mt-20 mb-20">
      <a-space :size="20">
        <a-select
          v-model:value="searchParams.source"
          placeholder="平台"
          style="width: 200px"
          allowClear
          option-label-prop="children"
        >
          <a-select-option
            v-for="item in platformOptions"
            :value="item?.key"
            :key="item?.key"
          >
            <a-image
              :preview="false"
              :width="20"
              :height="20"
              :src="item?.image"
            />
            &nbsp;{{ item?.value }}
          </a-select-option>
        </a-select>
        <!-- 更新时间 -->
        <a-select
          v-model:value="searchParams.status"
          placeholder="账号状态"
          :options="statusOptions"
          style="width: 200px"
          allowClear
        ></a-select>
        <a-input-search
          v-model:value="searchParams.nickname"
          placeholder="账号昵称"
          style="width: 200px"
          @search="handleSearch"
        >
        </a-input-search>
        <a-select
          v-model:value="searchParams.group_id"
          placeholder="分组"
          :options="groupList"
          :fieldNames="{ label: 'title', value: 'id' }"
          style="width: 200px"
          allowClear
        ></a-select>
        <a-space :size="10">
          <a-button
            type="primary"
            @click="() => ((page = 1), getUserAccount())"
          >
            <!-- @click="addGroup" -->
            查询
          </a-button>

          <a-button
            type="primary"
            ghost
            style="border: 1px solid #e0e0e6; color: #000; border-radius: 6px"
            @click="handleReset"
            >重置</a-button
          >
        </a-space>
      </a-space>
      <div >
        还可添加
        <span style="font-weight: 600; color: var(--ss-primary-color)">{{
          addTotal
        }}</span
        >个账号
        <a-button
            style="margin-left: 20px"
            type="primary"
            @click="clickLogin"
            >一键检测登录状态</a-button
          >
      </div>
    </div>
    <a-divider class="my-20"></a-divider>
    </template>

    <template #center>
      <a-table
      sticky
      :row-key="(record) => record.id"
      :loading="loading"
      :dataSource="dataSource"
      :columns="columns"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ x: 1800, }"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      class="table"
    >
      <template #headerCell="{ column }">
        <template v-if="column.dataIndex === 'status_txt'">
          <span style="margin-right: 10px">登录状态</span>
          <a-popover>
            <template #content>
              <div style="width: 520px">
                <div style="font-weight: 700;">为什么账号失效?</div>
                目前，{{
                  appName
                }}短视频已对接了市场上大多数主流平台，以实现账号管理和一键分发功能。为了获得平台的授权，用户需进行账号登录。而各个平台出于自身安全及用户操作等方面考虑，对账号设定了不同的授权时间限制，超过后需要重新登录以获取新的授权。这是为了确保账号的安全，因此我们系统不能绕过这些平台设定的机制。我们将努力在确保账号安全的前提下，尽量减少离线情况带来的影响。
              </div>
            </template>
            <question-circle-outlined />
          </a-popover>
        </template>

         <template v-if="column.dataIndex === 'poi'">
          <span style="margin-right: 10px">POI地址</span>
          <a-popover placement="right">
            <template #content>
              <div>
               仅抖音账号支持POI绑定
              </div>
            </template>
            <question-circle-outlined />
          </a-popover>
        </template>
      </template>
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.key == 'name'">
          <div class="table-name">
            <a-tooltip>
              <template #title>
                <span>{{ record?.nickname }}</span>
              </template>
              <a-avatar :size="40">
                <template #icon>
                  <img :src="record?.avatar" />
                </template>
              </a-avatar>
              <!-- <span class="nickname">{{ record?.nickname }}</span> -->
            </a-tooltip>
            <span class="nickname">{{ record?.nickname }}</span>
            <a-tooltip>
              <template #title
                >机构主号：{{
                  record?.user_expand_info?.parent_account?.nickname
                }}</template
              >
              <a-tag
                color="blue"
                style="cursor: pointer"
                v-if="
                  record?.user_expand_info?.account_type == 'org_sub' &&
                  record?.user_expand_info?.account_type_txt
                "
                >{{ record?.user_expand_info?.account_type_txt }}</a-tag
              >
            </a-tooltip>
            <a-tag
              color="purple"
              v-if="
                record?.user_expand_info?.account_type == 'org_main' &&
                record?.user_expand_info?.account_type_txt
              "
              >{{ record?.user_expand_info?.account_type_txt }}</a-tag
            >
            <a-tag
              v-if="
                record?.user_expand_info?.account_type == 'default' &&
                record?.user_expand_info?.account_type_txt
              "
              >{{ record?.user_expand_info?.account_type_txt }}</a-tag
            >
          </div>
        </template>
        <template v-if="column.key == 'source'">
          <a-row justify="start" align="middle" :gutter="[16,16]">
            <a-col>
                <a-image
                  :preview="false"
                  :width="40"
                  :height="40"
                  :src="
                    platformOptions?.find((it) => it?.key === record?.source)?.image
                  "
                />
            </a-col>
            <a-col>
              {{platformOptions?.find((it) => it?.key === record?.source)?.value }}
            </a-col>
          </a-row>
          
        </template>
        
        <template v-if="column.key == 'authorize_at'">
          <span> {{record?.authorize_at || '--'}} </span>
        </template>

        <template v-if="column.key == 'bindlecount'">
          <div>
           <a-popover>
            <template #content>
              <div style="width: 320px">
              <span v-for="(item, idnex) in record.bindAccount" style="margin-right: 10px;">
             {{ item?.team_user?.nickname }}
          </span>
              </div>
            </template>
             <div class="bindlecount"  v-if="record.bindAccount.length > 0">
             <span  v-for="(item, idnex) in record.bindAccount" style="margin-right: 10px;">
             {{ item?.team_user?.nickname }}
          </span>
          </div>
          </a-popover>


          <div  v-if="record.bindAccount.length == 0">
             --
          </div>

          </div>

         
        </template>

        
        <template v-if="column.key == 'status_txt'">
          <a-space
            :size="4"
            v-if="record?.status === 1"
            direction="vertical"
            style="display: flex; flex-direction: row; justify-content: center"
          >
            <a-tag :color="record?.status === 1 ? 'green' : 'red'">{{
              record.status_txt
            }}</a-tag>
            <a-tag
              v-if="record.status != 1"
              style="border-radius: 8px"
              color="#108ee980"
              >预计过期时间：{{ record?.created_at }}</a-tag
            >
          </a-space>
          <a-space :size="4" v-else direction="vertical">
            <div>
              <span style="color: #2878ff; margin-right: 10px">未登录</span>
            </div>

            <a-button
              v-if="record?.user_expand_info?.account_type != 'org_sub'"
              type="default"
              @click="
                showLoginModal(
                  record.source,
                  record.id,
                  record.platform.is_scan_authorize,
                  record.area_text
                )
              "
              >立即登录</a-button
            >
          </a-space>
        </template>
        <template v-if="column.key === 'env_status'">
          <a-space
            :size="4"
            v-if="record?.env_status == 1"
            direction="vertical"
            style="display: flex; flex-direction: row; justify-content: center"
          >
            <a-tag :color="record?.env_status == 1 ? 'green' : 'red'">
              <span v-if="record?.env_status == 1">已验证</span>
              <span v-else>{{ record?.env_ver_error || '验证失败' }}</span>
            </a-tag>
          </a-space>
        </template>
        <template v-if="column.key == 'groups'">
          <div
            v-if="record.platform_account_group_relation.length"
            style="cursor: pointer"
          >
            <a-popover>
              <template #content>
                <div>
                  <a-tag
                    :key="item.id"
                    v-for="item in record.platform_account_group_relation"
                  >
                    <div class="text-overflow" :title="item.title">
                      {{ item.title }}
                    </div>
                  </a-tag>
                </div>
              </template>
              <a-tag
                v-for="item in record.platform_account_group_relation.slice(
                  0,
                  3
                )"
                :key="item.id"
              >
                <div class="text-overflow" :title="item.title">
                  {{ item.title }}
                </div>
              </a-tag>
            </a-popover>
          </div>
          <div v-else>--</div>
        </template>
        <template v-if="column.key == 'area_text'">
          <div style="text-align: center;">
            {{ record.area_text || "--" }}

          </div>
        </template>
         <template v-if="column.key == 'poi'">
          {{ record?.poi?.store_name || "--" }}
        </template>
        <template v-if="column.key == 'updated_at'">
          {{ record.updated_at || "--" }}
        </template>

        <template v-if="column.key == 'remark'">
         <div style="width: 100%; height: 100%;">

          <template v-if="record?.edit">
            <a-tooltip placement="top">
          <template #title>
            <span>
              {{ (record?.remark??'暂无备注') || '暂无备注' }}
            </span>
          </template>
            <a-input :id="`remarkInput_${record?.id}`" v-model:value="record.remark" 
            @pressEnter="debounceEdit_end(record)"
            placeholder="请输入账号备注"
            :maxLength="100"
            @change="inputChange"
            @blur="remarkBlur(record)"
            >
              <template #suffix>
                <EnterOutlined class="edit_icon" @click.stop="debounceEdit_end(record)"/>
              </template>
            </a-input>
            </a-tooltip>
          </template>
          <template v-else>

            <template v-if="record?.remark">
              <a-tooltip placement="top">
          <template #title>
            <span>
              {{ (record?.remark??'--') || '--' }}
            </span>
          </template>
            <div @click="editRemark(record)" style="display: flex; cursor: pointer; width: 100%; gap: 2px; align-items: center;justify-content: center;">
              <span class="remark" >
                {{ (record?.remark??'--') || '--' }}
              </span>
              <EditOutlined/>
            </div>
            </a-tooltip>
          </template>

          <template v-else>
            <div @click="editRemark(record)" style="display: flex; cursor: pointer; width: 100%; gap: 2px; align-items: center;justify-content: center;">
              <span class="remark" >
                {{ (record?.remark??'--') || '--' }}
              </span>
              <EditOutlined/>
            </div>
          </template>
          </template>

         </div>
        </template>

        <template v-if="column.key == 'action'">
          <div>
            <div style="display:flex;justify-content:start">
            
              <a-space :size="20">
                <a-button
                  v-if="record?.user_expand_info?.account_type != 'org_sub'"
                  type="text"
                  style="color: #2878ff; padding: 0"
                  @click="showArea(record)"
                  >编辑地区</a-button
                >
                <a-popconfirm
                  title="确认删除该账号吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDelete(record)"
                >
                  <!-- <DeleteOutlined style="color: #2878ff" /> -->
                  <a-button type="link" style="padding: 0">删除</a-button>
                </a-popconfirm>
              </a-space>
            </div>
            <div style="display:flex;justify-content:start; align-items:center">
              <a-space :size="20">
                <a-button
                  type="link"
                  @click="goToTiktok(record)"
                  size="small"
                  style="padding: 0"
                  v-if="record.source == 'douyin' && record.sec_user_id"
                  >查看</a-button
                >
                <a-button
                  v-if="record.source == 'douyin'"
                  type="text"
                  style="color: #2878ff; padding: 0"
                  @click="openPOI(record)"
                  >绑定POI</a-button
                >
              </a-space>
             
            </div>
          </div>
        </template>
      </template>
    </a-table>
    </template>

    <template #footer>
    </template>

    </baseContent>
    <!-- <RouteTitle /> -->

    <!-- 添加账号 -->
    <Suspense>
      <AddAccountModal
        v-model:visible="visibleAuthorization"
        @logined="onConfirmAuthorization"
        @startSync="onStartSync"
      />
    </Suspense>
    <!-- 三方账号登录 -->
    <a-modal
      :visible="loginVisible"
      width="90vw"
      wrapClassName="account-modal"
      :closable="false"
      @cancel="closeLoginModal"
      :footer="null"
      style="height: 90vh; top: 5vh; padding-bottom: 0px"
      :forceRender="true"
      :zIndex="1003"
      :destroyOnClose="true"
    >
      <div class="w-full h-full">
        <Suspense>
          <AccountManage
            :app-key="appKey"
            @onError="onError"
            :accountId="appAcountId"
            ref="accountManageRef"
            @logined="onAccountLogined"
          >
            <template #header_after>
              <CloseOutlined class="cursor-pointer" @click="closeLoginModal" />
            </template>
          </AccountManage>
        </Suspense>
      </div>
    </a-modal>
    <!-- 新增分组 -->
    <AddGrouping
      :visible="visibleGrouping"
      @onCancel="onCancelGrouping"
      @onConfirm="onConfirmGrouping"
    />

    <!-- 账号详情 -->
    <AccountDetail
      :visible="visibleAccountDetail"
      :data="record"
      @onCancel="
        () => {
          record = {};
          visibleAccountDetail = false;
        }
      "
    />

    <!-- 二维码 -->
    <QRCode :visible="qRCodeVisible" @onCancel="qRCodeVisible = false" />

    <!-- 导出弹框 -->
    <ExportMdal :visible="visibleExport" @cacel="visibleExport = false" />
    <!-- 设置账号分组 -->
    <a-modal
      :visible="settingVisible"
      title="设置分组"
      centered
      :width="360"
      @cancel="onClose"
      @ok="settingGroup"
      :body-style="{
        padding: '10px 24px',
      }"
    >
      <a-form>
        <a-form-item label="分组" required>
          <a-select
            v-model:value="selectGroupId"
            placeholder="分组"
            style="width: 200px"
            allowClear
            :options="groupList"
            :fieldNames="{ value: 'id', label: 'title' }"
          >
            <template #dropdownRender="{ menuNode: menu }">
              <v-nodes :vnodes="menu" />
              <a-divider style="margin: 4px 0" />
              <div
                class="flex justify-center items-center cursor-pointer"
                style="align-items: center; color: var(--ss-primary-color)"
                @mousedown="(e) => e.preventDefault()"
                @click="addItem"
              >
                <plus-outlined />
                <span> 添加分组</span>
              </div>
            </template>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 新建账号分组 -->
    <AddAcountGroup
      v-model:visible="addVisible"
      :isShowAccount="false"
      @created="onAddGroup"
    ></AddAcountGroup>
  </div>

  <!-- 下载客户端 -->
  <DownloadModal
    v-model:visible="downLoadVisible"
    @close="downLoadVisible = false"
  />

  <NewAddPOIList
  :visible="visiblePOI"
  :platform_account_user_id="platform_account_user_id"
  :checked_poi = "checked_poi"
  @onClose ="poiclose"
  />

  <!-- 编辑地区 -->
  <EditRegion
    :visible="EditRegionVisible"
    :id="editId"
    @close="EditRegionVisible = false"
    @success="EditRegionSuccess"
  >
  </EditRegion>
  <!-- 同步弹窗组件 -->
  <InSyncModal
    ref="inSyncModal"
    @update="handleReset"
    :syncModalInfo="syncModalInfo"
  />
  <!-- 添加/编辑账号所在地区 -->
  <addArea
    v-model:visible="areaVisible"
    :id="acoountId"
    @success="onConfirmArea"
    :appKey="currentPlatformKey"
  ></addArea>
  <!-- 充值弹窗 -->
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

  <a-modal
    centered
    :width="800"
    v-model:visible="visible_index"
    title="选择员工"
     :maskClosable="false"
    @ok="handleOk_index"
  >
    <div class="index_content">
      <div
        class="content_item"
        v-for="(item, idnex) in index_list"
        :key="index"
      >
        <a-checkbox style="margin-right: 10px" v-model:checked="item.checked">
        </a-checkbox>
        <img
          :src="item.avatar"
          alt=""
          style="
            width: 50px;
            height: 50px;
            border-radius: 50px;
            margin-right: 10px;
          "
        />
        <div class="info">
          <div class="top">{{ item.nickname }}</div>
          <div class="bottom" style="font-size: 12px; color: rgb(161 161 161)">
            角色: {{ item.team_user_role.name }}
          </div>
        </div>
      </div>
    </div>

    <div
      style="display: flex; justify-content: flex-end"
      v-if="index_list.length > 0"
    >
      <a-pagination
        :total="index_total"
        v-model:current="index_page"
        v-model:pageSize="index_pageSize"
        show-less-items
        @change="PageChange"
      />
    </div>


    <div  v-if="index_list.length == 0">
      <a-empty />
    </div>
  </a-modal>


  <div class="baseModels">
    <a-modal v-model:visible="oneLoginVisible" :getContainer="'.baseModels'" :footer="null" :maskClosable="false" :width="500" centered >
    <div class="one-login" >
      <div class="spin">
        <a-spin :indicator="indicator"  />
      </div>
      <div>
        <span class="on-line-count">{{onLineCount}}</span>
        <span style="font-size: 26px;">/</span>
        <span class="account-count">{{accountCount}}</span>
      </div>
      <div style="font-size: 18px;color:#9fa5b3" >账号检测中...</div>
    </div>
  </a-modal>
  <a-modal v-model:visible="oneLoginResultVisible" :getContainer="'.baseModels'" :footer="null" :maskClosable="false" :width="500" centered >
    <div class="one-login" >
      <check-circle-filled class="circle-filled" />
      <div class="result-text">
        检测已完成
      </div>
      <div class="result-dec">
        本次检测共{{accountCount}}个账号，成功<span style="color: #2878ff">{{onLineCount}}</span> ，登录失效<span style="color:red">{{offLineCount}}</span> 
      </div>
      <a-row justify="center" :gutter="[16,16]">
        <a-col>
          <a-button type="primary" @click="loginClick('login')">登录失效账号</a-button>
        </a-col>
        <a-col>
          <a-button type="primary" ghost @click="loginClick('success')">完成</a-button>
        </a-col>
      </a-row>
    </div>
    </a-modal>
  </div>

  
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  onMounted,
  ref,
  createVNode,
  h,
  nextTick
} from "vue";
import {
  DownOutlined,
  SearchOutlined,
  UpOutlined,
  FormOutlined,
  CloseOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
  CheckCircleFilled,
  EnterOutlined,
  EditOutlined
} from "@ant-design/icons-vue";
import { message, Modal, notification } from "ant-design-vue";
// 添加账号弹窗组件
import AddAccountModal from "./modules/AccountAddModal.vue";
import AddGrouping from "./modules/AddGrouping.vue";
import NewAddPOIList from "./modules/newAddPOIList.vue";
import AccountDetail from "./modules/AccountDetail.vue";
import QRCode from "./modules/QRCode.vue";
import ExportMdal from "../components/ExportMdal/index.vue";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons-vue";
import AccountManage from "@/views/home/accountCenter/accountManage.vue";
import { useRoute, useRouter } from "vue-router";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils.js";
import store from "@/store/index";
import AddAcountGroup from "./modules/AddAcountGroup.vue";
import DownloadModal from "./modules/DownloadModal.vue";
// 编辑地区
import EditRegion from "./modules/EditRegion.vue";
import { onBeforeRouteLeave } from "vue-router";
import addArea from "./modules/AddArea.vue";
import { debounce } from "lodash";

import {
  getPlatformList,
  getUserAccountList,
  deleteUserAccount,
} from "./service/accountManageApi";
// 同步中弹窗组件
import InSyncModal from "./modules/InSyncModal.vue";

// 充值弹窗
import vipModal from "@/socialMedia/Vip/vipModal.vue";

import { LoadingOutlined } from '@ant-design/icons-vue';

// 基础模板组件
import baseContent from '@/components/baseContent/index.vue'

const INIT_PARAMS = {
  source: undefined,
  status: undefined,
  nickname: undefined,
  group_id: undefined,
};

export default defineComponent({
  name: "IpManage",
  components: {
    baseContent,
    vipModal,
    DownOutlined,
    SearchOutlined,
    UpOutlined,
    AddAccountModal,
    FormOutlined,
    AddGrouping,
    AccountDetail,
    QRCode,
    EditRegion,
    EditOutlined,
    ExportMdal,
    DeleteOutlined,
    AccountManage,
    CloseOutlined,
    CheckCircleFilled,
    EnterOutlined,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    PlusOutlined,
    AddAcountGroup,
    DownloadModal,
    InSyncModal,
    EllipsisOutlined,
    addArea,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
    NewAddPOIList
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    // 基础模版组件
    const baseContentRef = ref()

    const state = reactive({
      checked_poi: "",
      platform_account_user_id: "",
      visiblePOI: false,
      index_list: [],
      index_total: null,
      index_page: 1,
      index_pageSize: 10,
      visible_index: false,
      appName: '',
      vipVisible: false,
      bye: true,
      alldel_loading: false,
      addVisible: false,
      EditRegionVisible: false, // 编辑地区显示隐藏
      editId: null, // 选择地区的id
      addTotal: 0,
      selectGroupId: "",
      groupList: [],
      settingVisible: false,
      appKey: "",
      appAcountId: "",
      is_scan_authorize: false, //是否扫码授权
      loginVisible: false,
      searchParams: {
        ...INIT_PARAMS,
      },
      statusOptions: [
        {
          value: "1",
          label: "在线",
        },
        {
          value: "0",
          label: "未登录",
        },
      ],
      groupOptions: [],
      platformOptions: [],
      dataSource: [],
      columns: [
        {
          title: "序号",
          dataIndex: "id",
          key: "id",
          align: "center",
           width: 80,
        },
        {
          title: "账号",
          dataIndex: "name",
          key: "name",
          align: "center",
          width: 260,

        },
        {
          title: "平台",
          dataIndex: "source",
          key: "source",
          align: "center",
          width: 180,
        },
        {
          title: "登录状态",
          dataIndex: "status_txt",
          key: "status_txt",
          width: 160,
          align: "center",
        },
        {
          title: "发布环境验证",
          dataIndex: "env_status",
          key: "env_status",
          width: 160,
          align: "center",
        },
        {
          title: "上次授权时间",
          dataIndex: "authorize_at",
          key: "authorize_at",
          width: 180,
          align: "center",
        },
        {
          title: "账号备注",
          dataIndex: "remark",
          key: "remark",
          width: 180,
          align: "center",
        },
      
          {
          title: "绑定员工",
          dataIndex: "bindlecount",
            key: "bindlecount",
            align: "center",
          
          width: 180,
        },
        {
          title: "POI地址",
          dataIndex: "poi",
          key: "poi",
            align: "center",
          width: 200,
        },
        {
          title: "分组",
          dataIndex: "groups",
          key: "groups",
          align: "center",
          width: 200,
        },
        {
          title: "所在地区",
          dataIndex: "area_text",
          key: "area_text",
          align: "center",
          width: 200,
        },
       
        {
          title: "更新时间",
          dataIndex: "updated_at",
          key: "updated_at",
          width: 180,
          align: "center",
        },

        {
          title: "操作",
          dataIndex: "action",
          key: "action",
          width: 160,
          fixed: "right",
          align: "center",
        },
      ],
      record: {},

      selectedRowKeys: [],
      loading: false,
      page: 1,
      pageSize: 10,
      total: 0,

      visibleAuthorization: false,

      visibleGrouping: false,

      visibleAccountDetail: false,

      qRCodeVisible: false,

      visibleExport: false,

      downLoadVisible: false,
      inSyncModal: null, //同步弹窗组件实例
      syncModalInfo: {},
      org_count: 0,
      syncLoading: false,

      oneLoginVisible:false ,//一键登录弹框
      indicator:h(LoadingOutlined, {
        style: {
          fontSize: '32px',
        },
        spin: true,
      }),
      onLineCount:0,
      accountCount:0,
      offLineCount:0,
      oneLoginResultVisible:false
    });
    let areaVisible = ref(false);
    const onConfirmArea = () => {
      areaVisible.value = false;
      getUserAccount();
    };
    const handleSearch = () => {
      getUserAccount();
    };

    const handleReset = () => {
      state.searchParams = {
        ...INIT_PARAMS,
      };
      getUserAccount();
    };

    const onSelectChange = (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getUserAccount();
    };

    const addAuthorization = () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        state.vipVisible = true;
      } else {
        state.visibleAuthorization = true;
      }
    };
    const onCancelAuthorization = () => {
      state.visibleAuthorization = false;
    };

    const onConfirmAuthorization = () => {
      getUserAccount();
      state.visibleAuthorization = false;
    };

    const qrCodeClick = () => {
      state.qRCodeVisible = true;
    };

    // 新建分组
    const addGroup = () => {
      state.visibleGrouping = true;
    };
    const onCancelGrouping = () => {
      state.visibleGrouping = false;
    };
    const onConfirmGrouping = () => {
      state.visibleGrouping = false;
    };

    // 批量导出
    const exportClick = () => {
      state.visibleExport = true;
    };

    // 批量删除
    const batchDelete = () => {
      if (!state.selectedRowKeys.length) {
        message.error("请选择需要操作的数据");
        return;
      }
      Modal.confirm({
        title: "提示",
        icon: "",
        content: "确定批量删除吗？",
        cancelText: "取消",
        okText: "确定",
        onOk() {
          console.log("OK");
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    };

    // 账号详情
    const accountDetail = (record) => {
      state.record = record;
      state.visibleAccountDetail = true;
    };

    const handleDelete = (record) => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        state.vipVisible = true;
      } else {
        Modal.confirm({
          title: "提示",
          icon: "",
          content: "确定删除吗？",
          cancelText: "取消",
          okText: "确定",
          onOk() {
            console.log("OK");
            deleteUserAccount(record?.id).then(() => {
              getUserAccount();
            });
          },
          onCancel() {
            console.log("Cancel");
          },
        });
      }
    };

    const getUserAccount = () => {
      const params = {
        ...state.searchParams,
        page: state.page,
        pageSize: state.pageSize,
      };

      state.loading = true;
      getUserAccountList(params).then((res) => {
        state.loading = false;
        state.org_count = res?.org_count;
        res?.result.data.forEach((item, index) => {
          item.edit = false
        });
        state.dataSource = res?.result.data;


        console.log(state.dataSource,   '数据源111111231321321312');
        state.total = res?.result.total;
        state.addTotal = res.account_total;
      });
    };

    onMounted(() => {
      getUserAccount();
      getPlatformList({ filterShow: 1 }).then((res) => {
        state.platformOptions = res.result;
      });
      store.dispatch("getAiConfig").then((aiConfig) => {
        state.appName = aiConfig.site_name
      })
    });
    const showLoginModal = (key, id, is_scan_authorize, area_text) => {
      if (!area_text) {
        showArea({ id, key });
        return;
      }
      if (key == "kuaishou") {
        request
          .post("/work_ai", "/org/platform/account/user/authorize", {
            source: "kuaishou",
            id: id,
          })
          .then((res) => {
            if (res.result.url) {
              window.open(res.result.url, "_blank"); // 打开新窗口
            } else {
              return message.warning("获取授权链接失败");
            }
          })
          .catch((err) => {
            console.log(err);
          })
          .finally(() => {});
      } else {
        const env = import.meta.env.ELECTRON;
        if (!env) {
          // 网页端 下载软件
          state.downLoadVisible = true;
          return;
        }
        console.log(key);
        state.appKey = key;
        state.appAcountId = id;
        state.is_scan_authorize = is_scan_authorize;
        state.loginVisible = true;
      }
    };
    const closeLoginModal = () => {
      state.loginVisible = false;
    };
    // 发送第三方信息给后台接口
    const sendAccountInfo = (params) => {
      request
        .post("/work_ai", "/org/platform/account/user/sync", params)
        .then((res) => {
          message.success("授权成功");
          state.loginVisible = false;
          getUserAccount();
        })
        .catch((err) => {
          if (err.code == 37100) {
            message.error(err.msg);
          }
        });
    };
    const onAccountLogined = ({ appKey, headers }) => {
      if (state.is_scan_authorize) {
        //扫码授权
        message.success("授权成功");
        state.loginVisible = false;
        getUserAccount();
      } else {
        sendAccountInfo({
          org_id: utils.getOrgId(),
          header: headers,
          source: appKey,
          id: state.appAcountId,
          team_id: store.state.user.teamId,
        });
      }
    };
    const goToGroup = () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        state.vipVisible = true;
      } else {
        if (route.path.includes("socialMedia")) {
          router.push({
            name: "MediaAccountGroupList",
          });
        } else {
          router.push({
            name: "AccountGroupList",
          });
        }
      }
    };
    const getGroupList = () => {
      state.loading = true;
      request
        .get("/work_ai", "/org/platformAccount/group/list", {})
        .then((res) => {
          if (res.result) {
            state.groupList = res.result;
          }
          state.loading = false;
        });
    };
    getGroupList();
    const settingGroup = () => {
      let title = state.groupList.find(
        (item) => item.id == state.selectGroupId
      )?.title;
      let params = {
        title,
        account_id: state.selectedRowKeys,
        id: state.selectGroupId,
        noMove: 1,
      };
      if (!state.selectGroupId) {
        return message.warning("请选择分组");
      }
      request
        .put("/work_ai", "/org/platformAccount/group/update", params)
        .then((res) => {
          message.success("设置成功");
          state.settingVisible = false;
          getUserAccount();
          state.selectedRowKeys = [];
        });
    };
    const onClose = () => {
      state.settingVisible = false;
    };
    const showSettingGroup = () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        state.vipVisible = true;
      } else {
        if (state.selectedRowKeys.length === 0) {
          return message.warning("请选择要设置的账号");
        }
        state.settingVisible = true;
      }
    };
    const onError = () => {
      state.loginVisible = false;
    };
    const addItem = () => {
      state.addVisible = true;
    };
    const onAddGroup = () => {
      getGroupList();
    };

    // 编辑
    const editGroup = (data) => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        state.vipVisible = true;
      } else {
        state.editId = data.id;
        state.EditRegionVisible = true;
      }
    };
    // 编辑地区成功回调
    const EditRegionSuccess = () => {
      state.EditRegionVisible = false;
      getUserAccount();
    };
    // 开始同步
    const onStartSync = (info) => {
      if (!info || !info.sync_task_id) {
        return message.error("同步失败，同步状态id丢失");
      }
      state.syncModalInfo = {
        ...info,
        startBtnText: "同步中...",
        openType: "single",
      }; //赋值弹窗需要的信息
      state.inSyncModal && state.inSyncModal.showModal(); //打开弹窗
      state.inSyncModal && state.inSyncModal.showStartSyncFn(); //打开开始同步弹窗
      const timerId = setInterval(() => {
        request
          .get("/work_ai", "/user/socialMedia/douyin/process", {
            key: info.sync_task_id,
          })
          .then((successRes) => {
            if (successRes?.result?.status == "done") {
              clearInterval(timerId);
              state.inSyncModal && state.inSyncModal.closeStartSyncFn(); //关闭开始同步弹窗
              state.inSyncModal && state.inSyncModal.showEndSyncFn(); //开启完成同步弹窗同步弹窗
              state.syncModalInfo.sync_processed_num =
                successRes?.result?.sync_processed_num; //已同步账号数量
            }
          })
          .catch((error) => {
            // 清除定时器，关闭弹窗
            clearInterval(timerId);
            state.inSyncModal && state.inSyncModal.closeModal();
            state.inSyncModal && state.inSyncModal.closeStartSyncFn();
            state.inSyncModal && state.inSyncModal.showEndSyncFn();
          });
      }, 1000);
    };
    // 同步子账号
    const SynchronousAccount = () => {
      state.syncLoading = true;
      request
        .post("work_ai", "/user/socialMedia/douyin/syncSubOrgAccount")
        .then((res) => {
          console.log(res, "同步子账号");

          state.syncLoading = false;
          if (
            res.result &&
            res.result.sync_task_id &&
            res.result.sync_account > 0
          ) {
            // 抖音机构号
            state.syncModalInfo = {
              nickname: "抖音机构号",
              startBtnText: "开始同步",
              task_id: res.result?.sync_task_id,
              openType: "batch",
            };
            state.inSyncModal && state.inSyncModal.showModal();
            state.inSyncModal && state.inSyncModal.showStartSyncFn();
          }
          // else if (
          //   !res.result?.sync_task_id ||
          //   res.result?.sync_account < 1
          // ) {
          //   return message.error(res?.result?.msg);
          // }

          if (res?.result?.msg) {
            message.warning(res?.result?.msg);
          }
        })
        .catch((err) => {
          state.syncLoading = false;
        });
    };

    // 批量删除
    const all_del = () => {
      if (state.selectedRowKeys.length === 0) {
        return message.warning("请选择要删除的账号");
      }

      Modal.confirm({
        title: () => `确定要删除所选账号吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        cancelText: "取消",
        okText: "确定",
        onOk() {
          state.alldel_loading = true;
          deleteUserAccount(state.selectedRowKeys).then(() => {
            state.alldel_loading = false;
            message.success("删除成功!");
            getUserAccount();
          });
        },
      });
    };

    const debouncedall_del = debounce(all_del, 1000, {
      leading: true,
      trailing: false,
    });

    const all_index = () => {
      if (state.selectedRowKeys.length === 0) {
        return message.warning("请先选择账号");
      }
      state.visible_index = true;
      let params = {
        page: state.index_page,
        pageSize: state.index_pageSize,
      };
      request.get("work_ai", "/user/team/member/list", params).then((res) => {
        state.index_total = res.total;
        state.index_list = res.list.map((item) => ({
          ...item,
          checked: false,
        }));
      });
    };

    const debouncedall_index = debounce(all_index, 1000, {
      leading: true,
      trailing: false,
    });

    const PageChange = (page, pageSize) => {
      state.index_page = page;
      state.index_pageSize = pageSize;
      all_index();
    };

    const handleOk_index = async () => {
      let teamUserIds = [];
      state.index_list.forEach((item) => {
        if (item.checked) {
          teamUserIds.push(item.id);
        }
      });

      if (teamUserIds.length == 0) {
        return message.warning("请选择员工");
      } else {
        request
          .put("/work_ai", "/role/teamUser/platformAccount/batchAppend", {
            accountIds: state.selectedRowKeys,
            teamUserIds: teamUserIds,
          })
          .then((res) => {
            message.success("操作成功!");
            state.visible_index = false;
            state.userList = [];
            state.selectedRowKeys = [];
            getUserAccount();
          });
      }
    };

    onBeforeRouteLeave((to, from, next) => {
      state.bye = false;
      next(true);
    });
    let acoountId = ref("");
    let currentPlatformKey = ref("");
    const showArea = (record) => {
      acoountId.value = record.id;
      currentPlatformKey.value = record.source;
      areaVisible.value = true;
    };

    const openPOI = (info) => {
      state.visiblePOI = true
      state.platform_account_user_id = info?.id
      state.checked_poi = info?.poi?.id
    }

       // 前往抖音查看
    const goToTiktok =(record)=>{
        window.open(`https://www.douyin.com/user/${record.sec_user_id}`)
    }

    const poiclose = () => {
      state.visiblePOI = false
       state.checked_poi = ""
      getUserAccount()
    }
    
    const clickLogin=()=>{
      state.onLineCount = 0
      state.accountCount = 0
      state.offLineCount = 0
      request
          .get("/work_ai", "/platform/account/keep/alive").then((res)=>{
            state.oneLoginVisible = true
            let tiemr =setInterval(() => {
              request
              .get("/work_ai", "/platform/account/keepAlive/task",{task_id:res.result.task_id}).then((task)=>{
                state.onLineCount = task.result.onLineCount
                state.accountCount = task.result.accountCount
                state.offLineCount = task.result.offLineCount
                if(task.result.status=='done'){
                  state.oneLoginVisible = false
                  state.oneLoginResultVisible = true
                  clearInterval(tiemr)
                }
              })
            },1000)
          })
    }

    const loginClick=(key)=>{
      state.oneLoginResultVisible = false
      state.page = 1;
      state.pageSize = 10;
      state.searchParams.status = undefined
      if(key=='login'){
        state.searchParams.status = '0'
        getUserAccount()
      }
      getUserAccount()

    }

    // 复制的备注值
    const copyRemark = ref('')

    // 编辑账号的备注
    const editRemark = (record) => {
      const find = state.dataSource.find(ele => ele.edit == true)
      // 有正在编辑的项
      if (find) {
        // 还原原本的更改
        find.remark = copyRemark.value??''
        find.edit = false
      }
      console.log(record, '编辑账号的备注'); 
      copyRemark.value = record?.remark??''
      record.edit = true
      nextTick(() => {
        // 自动获取焦点
        document.getElementById(`remarkInput_${record?.id}`)?.focus()
      })
    }

    // 结束编辑
    const edit_end = async(record) => {
      console.log(record, '结束编辑了');
      // 调用接口, 成功正常保存 失败 则恢复 复制的备注值
      const params = {
        id: record.id,
        remark: record.remark??''
      }
      try {
        const res = await request.put("work_ai", "/user/platformAccount/user/update", params)
        console.log(res, '备注修改成功了嘛');
        message.success('编辑成功!')
      } catch (error) {
        record.remark = copyRemark.value??''
      } finally {
        record.edit = false
      }
    }

    // 节流
    const debounceEdit_end = debounce(edit_end, 300)

    const remarkBlur=(record)=>{
      debounceEdit_end(record)
    }


    const inputChange = (e) => {
      console.log(e,'change了???');
      
    }
    return {
      ...toRefs(state),
      debounceEdit_end,
      copyRemark,
      baseContentRef,
      inputChange,
      edit_end,
      editRemark,
      poiclose,
      handleSearch,
      handleReset,
      pagination,
      handleTableChange,
      addAuthorization,
      onCancelAuthorization,
      onConfirmAuthorization,
      onSelectChange,
      addGroup,
      onConfirmGrouping,
      onCancelGrouping,
      batchDelete,
      handleDelete,
      accountDetail,
      qrCodeClick,
      exportClick,
      showLoginModal,
      closeLoginModal,
      onAccountLogined,
      goToGroup,
      getUserAccount,
      onClose,
      settingGroup,
      showSettingGroup,
      onError,
      addItem,
      onAddGroup,
      editGroup,
      EditRegionSuccess,
      onStartSync,
      SynchronousAccount,
      areaVisible,
      onConfirmArea,
      acoountId,
      currentPlatformKey,
      showArea,
      all_del,
      debouncedall_del,
      debouncedall_index,
      handleOk_index,
      PageChange,
      openPOI,
      clickLogin,
      loginClick,
      goToTiktok,
      remarkBlur
    };
  },
});
</script>

<style lang="less" scoped>
.box {
  height: 100%;
  padding: 14px 14px 0;
  overflow: hidden;

}

.btn-style {
  background: #2878ff;
}

.table {
  .table-name {
    width: 100%;
    height: 100%;
    display: flex;
    cursor: pointer;
    align-items: center;

    .nickname {
      margin: 0 6px;
      text-align: left; 
      // height: 40px;
      // display: inline-block;
      // overflow: hidden;
      // white-space: nowrap;
      // text-overflow: ellipsis;
      // max-width: 90px;
    }

    .tipStatus {
      position: absolute;
      bottom: -8px;
      left: 12px;
      width: 55px;
      color: #fff;
      border-radius: 10px;
      background: rgb(68, 191, 134);
      padding: 0 5px;
    }

    .text {
      transition: all 0.3s;
    }

    &:hover {
      color: #2878ff;
    }
  }

  .form-outlined {
    color: #ff8a87;
    cursor: pointer;
  }

  .save-btn {
    color: #2878ff;
    cursor: pointer;
  }

  .cancel-btn {
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      color: #ff8a87;
    }
  }

  // 编辑的回车图标
  .edit_icon{
    cursor: pointer;
    &:hover{
      transition: all .3s;
      color: var(--ss-primary-color-hover);
    }
  }

  .remark{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    width: auto;
    cursor: pointer;
  }

}

:deep(.ant-tabs-top > .ant-tabs-nav) {
  margin: 0;
}

button {
  border-radius: 5px;
}

.text-overflow {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.btn-primary {
  color: var(--ss-primary-color);
  border-color: var(--ss-primary-color);
}

.smart-clip-header {
  padding: 16px 30px 0;
  border-radius: 12px;
  height: 132px;
  min-width: 1140px;
  // margin-top: 20px;
  background: linear-gradient(220deg, #f3f7ff, rgba(159, 191, 255, 0.4));
  display: flex;
  flex-direction: column;

  .smart-clip-header-title_top {
    font-size: 24px;
    color: #0c0d0e;
    line-height: 1.5;
  }

  .smart-clip-header-desc {
    font-size: 14px;
    color: #737a87;
    margin-top: 5px;
    line-height: 1.5;
  }

  .smart-clip-header-btngroup {
    margin-top: 15px;
  }
}

.index_content {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  // padding: 20px;
  .content_item {
    width: 32%;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    margin-right: 10px;
  }
}

.bindlecount{
  width: 160px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}


// 设置弹窗圆角
.baseModels {
  .one-login{
  text-align: center;
  .spin{
    width: 50px;
    height: 50px;
    line-height: 50px;
     background: rgb(244, 247, 254);
     border-radius: 50%;
     margin: 20px auto
  }
  .on-line-count{
    font-size: 26px;
    font-weight: 600;
    color: #7058c6;
  }
  .account-count{
    font-size: 24px;

  }
  .circle-filled{
    color:#38cfc0;
    font-size: 42px;
    margin-top: 40px
  }
  .result-text{
    font-weight:700;
    font-size: 20px;
    margin: 20px 0 10px 17px;
  }
  .result-dec{
    margin-bottom: 20px;
    color:#9fb0bd;
    font-size: 18px;
  }

}
  :deep(.ss-modal-content) {
    border-radius: 10px !important;
    overflow: hidden;
  }
}

:deep(.ss-table-sticky-holder) {
  top: -10px !important;
}

</style>

